package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//通过配置使下面的映射都在/users
@RequestMapping(value="/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping(value = "/")
    public List<User> userList() {
        return userRepository.findAll();
    }

    /**
     * 新建一个用户
     * @Param name
     * @Param age
     */
    @PostMapping(value = "/")
    public String create(@RequestParam("name") String name,
                         @RequestParam("age") Integer age) {
        User user = new User();
        user.setName(name);
        user.setAge(age);
        userRepository.save(user);
        return "Success";
    }

    /**
     * 根据id的值来进行查询
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    public User findbyid(@PathVariable("id") Integer id) {
        return userRepository.findById(id).orElse(null);
    }

    /**
     * 根据id值对user信息进行更新
     * @param id
     * @param name
     * @param age
     */
    @PutMapping(value = "/{id}")
    public void updatebyid(@PathVariable("id") Integer id,
                       @RequestParam("name") String name,
                       @RequestParam("age") Integer age) {
        User user = new User();
        user.setId(id);
        user.setAge(age);
        user.setName(name);

        userRepository.save(user);
    }

    @DeleteMapping(value = "/{id}")
    public void deletebyid(@PathVariable("id") Integer id) {
        userRepository.deleteById(id);
    }
}
